package com.wanpinghui.supplier.object;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.SharedElementCallback;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.githang.statusbar.StatusBarCompat;
import com.wanpinghui.supplier.Config;
import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.addrbook.AddrBookFragment;
import com.wanpinghui.supplier.business.BusinessCircleFragment;
import com.wanpinghui.supplier.common.BaseActivity;
import com.wanpinghui.supplier.common.BaseFragment;
import com.wanpinghui.supplier.common.adapter.FragmentViewPagerAdapter;
import com.wanpinghui.supplier.message.MessageFragment;
import com.wanpinghui.supplier.message.nim.NimManager;
import com.wanpinghui.supplier.oauth.InputInfoActivity;
import com.wanpinghui.supplier.oauth.LoginUtil;
import com.wanpinghui.supplier.product.ProductListFragment;
import com.wanpinghui.supplier.user.BusinessScopeActivity;
import com.wanpinghui.supplier.user.MineFragment;
import com.wanpinghui.supplier.widgets.CountTextView;
import com.wanpinghui.supplier.widgets.NoScrollViewPager;
import com.wanpinghui.wphlibrary.WPHSdk;
import com.wanpinghui.wphlibrary.common.dialog.BaseDialogManager;
import com.wanpinghui.wphlibrary.common.dialog.YunBaseDialog;
import com.wanpinghui.wphlibrary.model.base.AppUpdateManager;
import com.wanpinghui.wphlibrary.model.base.bean.AppInfoBean;
import com.wanpinghui.wphlibrary.model.message.bean.CustomerNotificationContent;
import com.wanpinghui.wphlibrary.model.oauth.OAuthService;
import com.wanpinghui.wphlibrary.model.oauth.bean.UserBean;
import com.yunshl.yunshllibrary.manager.UpdateManager;
import com.yunshl.yunshllibrary.permission.MPermission;
import com.yunshl.yunshllibrary.storage.ShareDataManager;
import com.yunshl.yunshllibrary.storage.SharedPreferencesKey;
import com.yunshl.yunshllibrary.utils.DevicesUtil;
import com.yunshl.yunshllibrary.utils.LogUtils;
import com.yunshl.yunshllibrary.utils.SystemUtil;
import com.yunshl.yunshllibrary.utils.TextUtil;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import retrofit.callback.YRequestCallback;

/***
 * 功能描述:
 * 作者:qiujialiu
 * 时间:2017/11/22
 ***/
@ContentView(R.layout.layout_activity_homepage)
public class HomePageActivity extends BaseActivity {
    @ViewInject(R.id.viewpager_main)
    private NoScrollViewPager mViewPager;
    @ViewInject(R.id.ll_nvg_1)
    private LinearLayout mLayoutNvgMessage;
    @ViewInject(R.id.ll_nvg_2)
    private LinearLayout mLayoutNvgObject;
    @ViewInject(R.id.ll_nvg_3)
    private LinearLayout mLayoutNvgMine;
    @ViewInject(R.id.ll_nvg_4)
    private LinearLayout mLayoutNvgBook;
    @ViewInject(R.id.ll_nvg_5)
    private LinearLayout mLayoutNvgProduct;
    @ViewInject(R.id.iv_checkbox_image1)
    private ImageView mImageViewCheck1;
    @ViewInject(R.id.iv_checkbox_image2)
    private ImageView mImageViewCheck2;
    @ViewInject(R.id.iv_checkbox_image3)
    private ImageView mImageViewCheck3;
    @ViewInject(R.id.iv_checkbox_image4)
    private ImageView mImageViewCheck4;
    @ViewInject(R.id.iv_checkbox_image5)
    private ImageView mImageViewCheck5;
    @ViewInject(R.id.tv_checkbox_text1)
    private TextView mTextViewCheck1;
    @ViewInject(R.id.tv_checkbox_text2)
    private TextView mTextViewCheck2;
    @ViewInject(R.id.tv_checkbox_text3)
    private TextView mTextViewCheck3;
    @ViewInject(R.id.tv_checkbox_text4)
    private TextView mTextViewCheck4;
    @ViewInject(R.id.tv_checkbox_text5)
    private TextView mTextViewCheck5;
    @ViewInject(R.id.tv_message_count)
    private CountTextView mTextViewMessageCount;
    @ViewInject(R.id.tv_addrbook_count)
    private CountTextView tv_addrbook_count;
    @ViewInject(R.id.root_view)
    private LinearLayout layoutRoot;
    @ViewInject(R.id.view_dynamic_new)
    private View viewDynamicNew;


    private FragmentViewPagerAdapter mainViewPagerAdapter;
    private List<BaseFragment> mFragments;
    private ObjectFragment objectFragment;
    private MessageFragment messageFragment;
    private MineFragment mineFragment;
    private AddrBookFragment mBookFragment;
    private ProductListFragment mProductFragment;
    private BusinessCircleFragment circleFragment;
    private AppUpdateManager appUpdateManager;
    private int updateCount;
    private boolean setUpdate;
    private boolean haveCheck;
    private Bundle mReenterState;

    @Override
    public String getName() {
        return null;
    }

    @Override
    public boolean isBar() {
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                StatusBarCompat.setStatusBarColor(this, Color.WHITE, true);
            }else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    getWindow().setStatusBarColor(Color.TRANSPARENT);
                }
            }
        }
        layoutRoot.setPadding(0, DevicesUtil.getStatusBarHeight(this),0,0);
    }

    @Override
    protected void setStatusBarColor() {
//        try {
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                StatusBarCompat.setStatusBarColor(this, Color.WHITE, true);
//            } else {
//                if (SystemUtil.checkIsMeizuRom() || SystemUtil.isMIUI()) {
//                    StatusBarCompat.setStatusBarColor(this, Color.WHITE, true);
//                }else if (Build.VERSION.SDK_INT >= 21) {
//                    getWindow().setStatusBarColor(Color.TRANSPARENT);
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    @Override
    public void initViews() {
        if (getIntent() != null) {
            haveCheck = getIntent().getBooleanExtra("check", false);
        }
       /* if (Config.VERSION == 1) {
            mLayoutNvgProduct.setVisibility(View.GONE);
            mLayoutNvgBook.setVisibility(View.GONE);
        } else {
            mLayoutNvgProduct.setVisibility(View.VISIBLE);
            mLayoutNvgBook.setVisibility(View.VISIBLE);
        }*/
        addFragment();
        mainViewPagerAdapter = new FragmentViewPagerAdapter(getSupportFragmentManager(), mFragments);
        mViewPager.setAdapter(mainViewPagerAdapter);
        mViewPager.setScanScroll(false);
        mViewPager.setOffscreenPageLimit(2);//设置缓存view 的个数
        /*if (Config.VERSION > 1) {
            mViewPager.setOffscreenPageLimit(5);//设置缓存view 的个数
        } else {
            mViewPager.setOffscreenPageLimit(3);//设置缓存view 的个数
        }*/
        appUpdateManager = new AppUpdateManager(this);
    }

    private void addFragment() {
        mFragments = new ArrayList<>();
        messageFragment = new MessageFragment();
        mineFragment = new MineFragment();
        mFragments.add(messageFragment);
        mFragments.add(mineFragment);
        /*mFragments = new ArrayList<>();
        objectFragment = new ObjectFragment();
        messageFragment = new MessageFragment();
        mineFragment = new MineFragment();
        circleFragment = new BusinessCircleFragment();

        mFragments.add(messageFragment);
        if (Config.VERSION > 1) {
            mBookFragment = new AddrBookFragment();
            mFragments.add(mBookFragment);
        }
        if (Config.VERSION == 3) {
            mFragments.add(circleFragment);
        }else {
            mFragments.add(objectFragment);
        }
        if (Config.VERSION > 1) {
            mProductFragment = new ProductListFragment();
            mFragments.add(mProductFragment);
        }
        mFragments.add(mineFragment);*/
    }

    @Override
    public void bindEvents() {
        mLayoutNvgMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (LoginUtil.loginFilter(HomePageActivity.this)) {
                    mViewPager.setCurrentItem(Config.getMessagePage());
                }
            }
        });
        mLayoutNvgObject.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mViewPager.setCurrentItem(Config.getObjectPage());
            }
        });
        mLayoutNvgMine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (LoginUtil.loginFilter(HomePageActivity.this)) {
                    mViewPager.setCurrentItem(Config.getMinePage());
                }
            }
        });

        mLayoutNvgBook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (LoginUtil.loginFilter(HomePageActivity.this)) {
                    mViewPager.setCurrentItem(Config.getBookPage());
                }
            }
        });

        mLayoutNvgProduct.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mViewPager.setCurrentItem(Config.getProductPage());
            }
        });

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                setSelected(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void initData() {
        mImageViewCheck1.setSelected(true);
        mTextViewCheck1.setSelected(true);
        mImageViewCheck2.setSelected(false);
        mTextViewCheck2.setSelected(false);
        mImageViewCheck3.setSelected(false);
        mTextViewCheck3.setSelected(false);
        mImageViewCheck4.setSelected(false);
        mTextViewCheck4.setSelected(false);
        mImageViewCheck5.setSelected(false);
        mTextViewCheck5.setSelected(false);
        MPermission.with(this).permissions(/*Manifest.permission.RECORD_AUDIO,*/ Manifest.permission.CALL_PHONE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_CONTACTS).request();
        if (LoginUtil.isLogin()) {
            setSelected(0);
            mViewPager.setCurrentItem(0);
            if (!haveCheck) {
                UserBean userBean = WPHSdk.getService(OAuthService.class).getUserInfo(null);
                if (!userBean.isWholeInfo()) {
                    showImproveInfoDialog();
                } else if (!userBean.haveSerBusiness()) {
                    showSetBusinessDialog();
                }
            }
        } else {
            setSelected(Config.getObjectPage());
            mViewPager.setCurrentItem(Config.getObjectPage());
        }

        appUpdateManager.checkVersion(new YRequestCallback<AppInfoBean>() {
            @Override
            public void onSuccess(AppInfoBean var1) {
                if (AppUpdateManager.haveNewVersion(var1)) {
                    showUpdateDialog(var1.getUrl());
                }
            }

            @Override
            public void onFailed(int var1, String message) {

            }

            @Override
            public void onException(Throwable var1) {

            }
        });
    }

    public void setUpdateCount() {
        objectFragment.setNewestTime(System.currentTimeMillis());
    }

    public void showUpdateCount(int count) {
        if (count > 0) {
            showWarningText("更新" + count + "条新动态", ContextCompat.getColor(HomePageActivity.this, R.color.color_b5cef9));
        } else {
            showWarningText("暂时没有更多更新", ContextCompat.getColor(HomePageActivity.this, R.color.color_b5cef9));
        }
    }


    private void showSetBusinessDialog() {
        BaseDialogManager.getInstance().getBuilder(this)
                .setIcon(ContextCompat.getDrawable(this, R.mipmap.dialog_box_icon_business_scope))
                .setTitle("设置业务范围")
                .setMessage("设置您服务的业务范围\n方便我们推送您需要的订单信息")
                .setRightButtonText("好的，去设置")
                .setOnClickListener(new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(HomePageActivity.this, BusinessScopeActivity.class);
                        startActivity(intent);
                        dialog.dismiss();
                    }
                }).create().show();
    }

    private void showImproveInfoDialog() {
        BaseDialogManager.getInstance().getBuilder(this)
                .setIcon(ContextCompat.getDrawable(this, R.mipmap.dialog_box_icon_personage))
                .setTitle("完善个人资料")
                .setMessage("尊敬的会员，请及时完善您的个人资料\n以免影响您的正常使用")
                .setRightButtonText("好的，去完善")
                .setOnClickListener(new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(HomePageActivity.this, InputInfoActivity.class);
                        startActivity(intent);
                        dialog.dismiss();
                    }
                }).create().show();
    }

    private void setSelected(int index) {
        if (index == 0) {
            mImageViewCheck1.setSelected(true);
            mTextViewCheck1.setSelected(true);
            mImageViewCheck2.setSelected(false);
            mTextViewCheck2.setSelected(false);
            mImageViewCheck3.setSelected(false);
            mTextViewCheck3.setSelected(false);
            mImageViewCheck4.setSelected(false);
            mTextViewCheck4.setSelected(false);
            mImageViewCheck5.setSelected(false);
            mTextViewCheck5.setSelected(false);
        } else {
            mImageViewCheck1.setSelected(false);
            mTextViewCheck1.setSelected(false);
            mImageViewCheck2.setSelected(false);
            mTextViewCheck2.setSelected(false);
            mImageViewCheck3.setSelected(true);
            mTextViewCheck3.setSelected(true);
            mImageViewCheck4.setSelected(false);
            mTextViewCheck4.setSelected(false);
            mImageViewCheck5.setSelected(false);
            mTextViewCheck5.setSelected(false);
        }

       /* if (Config.VERSION == 1) {
            if (index == 0) {
                mImageViewCheck1.setSelected(true);
                mTextViewCheck1.setSelected(true);
                mImageViewCheck2.setSelected(false);
                mTextViewCheck2.setSelected(false);
                mImageViewCheck3.setSelected(false);
                mTextViewCheck3.setSelected(false);
            } else if (index == 1) {
                mImageViewCheck1.setSelected(false);
                mTextViewCheck1.setSelected(false);
                mImageViewCheck2.setSelected(true);
                mTextViewCheck2.setSelected(true);
                mImageViewCheck3.setSelected(false);
                mTextViewCheck3.setSelected(false);
            } else if (index == 2) {
                mImageViewCheck1.setSelected(false);
                mTextViewCheck1.setSelected(false);
                mImageViewCheck2.setSelected(false);
                mTextViewCheck2.setSelected(false);
                mImageViewCheck3.setSelected(true);
                mTextViewCheck3.setSelected(true);
            }
        } else {
            if (index == 0) {
                mImageViewCheck1.setSelected(true);
                mTextViewCheck1.setSelected(true);
                mImageViewCheck2.setSelected(false);
                mTextViewCheck2.setSelected(false);
                mImageViewCheck3.setSelected(false);
                mTextViewCheck3.setSelected(false);
                mImageViewCheck4.setSelected(false);
                mTextViewCheck4.setSelected(false);
                mImageViewCheck5.setSelected(false);
                mTextViewCheck5.setSelected(false);
            } else if (index == 1) {
                mImageViewCheck1.setSelected(false);
                mTextViewCheck1.setSelected(false);
                mImageViewCheck2.setSelected(false);
                mTextViewCheck2.setSelected(false);
                mImageViewCheck3.setSelected(false);
                mTextViewCheck3.setSelected(false);
                mImageViewCheck4.setSelected(true);
                mTextViewCheck4.setSelected(true);
                mImageViewCheck5.setSelected(false);
                mTextViewCheck5.setSelected(false);
            } else if (index == 2) {
                mImageViewCheck1.setSelected(false);
                mTextViewCheck1.setSelected(false);
                mImageViewCheck2.setSelected(true);
                mTextViewCheck2.setSelected(true);
                mImageViewCheck3.setSelected(false);
                mTextViewCheck3.setSelected(false);
                mImageViewCheck4.setSelected(false);
                mTextViewCheck4.setSelected(false);
                mImageViewCheck5.setSelected(false);
                mTextViewCheck5.setSelected(false);
            } else if (index == 3) {
                mImageViewCheck1.setSelected(false);
                mTextViewCheck1.setSelected(false);
                mImageViewCheck2.setSelected(false);
                mTextViewCheck2.setSelected(false);
                mImageViewCheck3.setSelected(false);
                mTextViewCheck3.setSelected(false);
                mImageViewCheck4.setSelected(false);
                mTextViewCheck4.setSelected(false);
                mImageViewCheck5.setSelected(true);
                mTextViewCheck5.setSelected(true);
            } else if (index == 4) {
                mImageViewCheck1.setSelected(false);
                mTextViewCheck1.setSelected(false);
                mImageViewCheck2.setSelected(false);
                mTextViewCheck2.setSelected(false);
                mImageViewCheck3.setSelected(true);
                mTextViewCheck3.setSelected(true);
                mImageViewCheck4.setSelected(false);
                mTextViewCheck4.setSelected(false);
                mImageViewCheck5.setSelected(false);
                mTextViewCheck5.setSelected(false);
            }
        }*/
    }

    public void setMessageCount(int count) {
        mTextViewMessageCount.setCount(count);
    }

    public void setAddrbookCount(int count) {
        tv_addrbook_count.setCount(count);
    }

    public void goPage(int index) {
        if (index >= 0 && index < mFragments.size()) {
            if (mViewPager != null) {
                mViewPager.setCurrentItem(index);
            }
        }
    }

    private String filePath;

    public void showUpdateDialog(final String url) {
        long lastTime = ShareDataManager.getInstance().getParaLong(SharedPreferencesKey.KEY_SAVE_UPDATE_TIME);
        if (System.currentTimeMillis() - lastTime < (259_200_000)) {
            return;
        }
        filePath = null;
        View view = LayoutInflater.from(this).inflate(R.layout.view_dialog_update_app, null);
        final Button button = (Button) view.findViewById(R.id.btn_right);
        final TextView textViewContext = (TextView) view.findViewById(R.id.tv_content);
        final LinearLayout layoutProgress = (LinearLayout) view.findViewById(R.id.ll_progress);
        final ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
        final TextView textViewProgress = (TextView) view.findViewById(R.id.tv_progress);
        final View view1 = view.findViewById(R.id.view1);
        final View view2 = view.findViewById(R.id.view2);
        final YunBaseDialog dialog = BaseDialogManager.getInstance().getBuilder(this).setContentView(view).create();
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtil.equals("立即更新", button.getText().toString())) {
                    appUpdateManager.downloadApp(url, new UpdateManager.IDownloadStatus() {
                        @Override
                        public void downloadFinish(String fileName) {
                            button.setEnabled(true);
                            button.setText("完成");
                            progressBar.setProgress(1000);
                            filePath = fileName;

                            textViewProgress.setText("100%");
                            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view1.getLayoutParams();
                            layoutParams.weight = 10;
                            view1.setLayoutParams(layoutParams);

                            LinearLayout.LayoutParams layoutParams2 = (LinearLayout.LayoutParams) view2.getLayoutParams();
                            layoutParams2.weight = 0;
                            view2.setLayoutParams(layoutParams2);
                        }

                        @Override
                        public void downloadPause() {

                        }

                        @Override
                        public void downloadStart(long fileLength) {
                            button.setEnabled(false);
                            button.setText("正在更新");
                            textViewContext.setVisibility(View.GONE);
                            layoutProgress.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void downLoading(int progress, int second) {
                            progressBar.setProgress(progress);
                            textViewProgress.setText((progress / 10) + "%");
                            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view1.getLayoutParams();
                            layoutParams.weight = progress;
                            view1.setLayoutParams(layoutParams);

                            LinearLayout.LayoutParams layoutParams2 = (LinearLayout.LayoutParams) view2.getLayoutParams();
                            layoutParams2.weight = 1000 - progress;
                            view2.setLayoutParams(layoutParams2);
                        }

                        @Override
                        public void downLoadError(String message) {

                        }
                    });
                } else if (TextUtil.equals("完成", button.getText().toString())) {
                    dialog.dismiss();
                    install(filePath);
                } else {
                    dialog.dismiss();
                }
            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                ShareDataManager.getInstance().save(HomePageActivity.this, SharedPreferencesKey.KEY_SAVE_UPDATE_TIME, System.currentTimeMillis());
            }
        });
        dialog.show();
    }


    private void install(String filePath) {
        File apkFile = new File(filePath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 24) {
            LogUtils.d("HomePage", "版本大于 N ，开始使用 fileProvider 进行安装");
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(
                    HomePageActivity.this
                    , "com.wanpinghui.supplier.fileprovider"
                    , apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            LogUtils.d("HomePage", "正常进行安装");
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        startActivity(intent);
    }

    /**
     * 接管Activity的setExitSharedElementCallback
     * @param activity
     */
    public void setSharedElementCallback(Activity activity){
        ActivityCompat.setExitSharedElementCallback(activity, new SharedElementCallback() {
            @Override
            public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) {
                if (mReenterState!=null){
                    int index = mReenterState.getInt("index",0);
                    sharedElements.clear();
                    sharedElements.put("tansition_view",circleFragment.getImageView(index));
                    mReenterState = null;
                }
            }
        });

    }
    @Override
    public void onActivityReenter(int resultCode, Intent data) {
        super.onActivityReenter(resultCode, data);
        mReenterState = new Bundle(data.getExtras());
    }

    public void showDynamicNewPoint() {
        viewDynamicNew.setVisibility(View.VISIBLE);
    }

    public void hideDynamicNewPoint() {
        viewDynamicNew.setVisibility(View.GONE);
    }
}
